<template>
  <page-wrap stay-still back hide-tab title="顾问基本信息">
    <view class="basic">
      <view class="basic-form-wrap">
        <u-form
          class="basic-form"
          label-position="top"
          ref="uForm"
          :model="form"
          :error-type="['message']"
        >
          <view class="form-item-wrap" @click="handleAvatar">
            <u-form-item class="avatar-wrap pick">
              <text class="label">头像</text>
              <image class="avatar" :src="form.pic"></image>
            </u-form-item>
          </view>
          <block v-for="(item, index) in formList" :key="index">
            <view
              class="form-item-wrap"
              v-if="!item.baseOn || form[item.baseOn.prop] == item.baseOn.value"
              @click.capture="handleSelect(item, index)"
            >
              <u-form-item
                :class="{ pick: item.comp }"
                :label="item.label"
                :prop="item.prop"
              >
                <u-input
                  class="form-input"
                  v-model="form[item.prop]"
                  :disabled="!!item.comp"
                  :placeholder="item.inputPlaceholder"
                  :clearable="false"
                />
                <!-- 下拉选择 -->
                <u-select
                  class="form-select"
                  v-model="item.show"
                  :list="item.data"
                  v-if="item.comp === 'select'"
                  @confirm="handleConfirm($event, item)"
                ></u-select>
                <!-- 时间选择 -->
                <u-picker
                  class="form-time"
                  mode="time"
                  v-model="item.show"
                  :params="item.param"
                  :start-year="item.start"
                  :end-year="item.end"
                  :default-time="form[item.prop]"
                  v-if="item.comp === 'time'"
                  @confirm="handleConfirm($event, item)"
                ></u-picker>
                <!-- 地点选择 -->
                <u-popup
                  class="form-region"
                  v-model="item.show"
                  mode="bottom"
                  z-index="100"
                  safe-area-inset-bottom
                  v-if="item.comp === 'region'"
                >
                  <view class="u-flex u-row-between btn-group">
                    <text class="cancel" @click="handleShow(item)">取消</text>
                    <text
                      class="confirm"
                      type="primary"
                      size="medium"
                      @click="handleShow(item)"
                      >保存</text
                    >
                  </view>
                  <scroll-view scroll-y="true" style="height: 50vh">
                    <region-filter
                      limit
                      :form-data="form[item.propVal]"
                      :prop-list="item.propList"
                      @confirm="handleRegionId(arguments, index)"
                    ></region-filter>
                  </scroll-view>
                </u-popup>
                <!-- 验证弹窗 -->
                <u-popup
                  class="form-cms"
                  mode="center"
                  border-radius="24"
                  width="88%"
                  z-index="100"
                  v-model="item.show"
                  v-if="item.comp === 'cms'"
                  closeable
                >
                  <view class="fc-wrap">
                    <view class="title">{{ item.title }}</view>
                    <u-field
                      v-model="item.target"
                      :placeholder="item.placeholder"
                      placeholder-style="color: #bbbbbb;"
                      :type="item.type === 'mobile' ? 'number' : ''"
                      label-width="0"
                      :clearable="false"
                    ></u-field>
                    <u-field
                      v-model="item.code"
                      placeholder="请输入验证码"
                      placeholder-style="color: #bbbbbb;"
                      type="number"
                      label-width="0"
                      :clearable="false"
                      @confirm="handleBind(item)"
                    >
                      <text
                        class="send-code"
                        slot="right"
                        @click="handleCms(item)"
                        >{{ item.codeText }}</text
                      >
                    </u-field>
                    <u-button
                      class="confirm-btn"
                      type="primary"
                      block
                      @click="handleBind(item)"
                      >确认</u-button
                    >
                  </view>
                </u-popup>
              </u-form-item>
            </view>
          </block>
        </u-form>
      </view>
      <u-button
        class="save-btn"
        type="primary"
        :loading="loading"
        @click="handleSave"
        >保存</u-button
      >
    </view>
  </page-wrap>
</template>

<script>
// import region from "@/utils/region.min";
import { formatTime, insertDefault } from "@/utils/handle";
import { getFileByUrl } from "@/api/index";
import {
  checkCanBind,
  sendBindCode,
  checkBindCode,
  uploadAction,
  uploadBaseUrl,
  uploadAvatar,
} from "@/api/index";
import { editConsultant, ztConsultantInfo } from "@/api/modules/career";
import RegionFilter from "@/components/RegionFilter";
import ShareMixin from "@/mixins/share";
export default {
  mixins: [ShareMixin],
  components: {
    RegionFilter,
  },
  data() {
    return {
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      userInfo: {},
      form: {},
      formList: [
        {
          label: "姓名",
          prop: "iname",
          inputPlaceholder: "请输入姓名",
        },
        {
          label: "性别",
          prop: "sex",
          inputPlaceholder: "请选择性别",
          comp: "select",
          data: [
            {
              label: "男",
              value: "男",
            },
            {
              label: "女",
              value: "女",
            },
          ],
          show: false,
        },
        {
          label: "出生日期",
          prop: "bday",
          inputPlaceholder: "请选择出生日期",
          comp: "time",
          param: {
            year: true,
            month: true,
            day: true,
            hour: false,
            minute: false,
            second: false,
          },
          start: new Date().getFullYear() - 70,
          end: new Date().getFullYear(),
          show: false,
        },
        {
          label: "现居住地",
          prop: "regionName",
          propVal: "regionid",
          inputPlaceholder: "请选择现居住地",
          comp: "region",
          show: false,
          propList: ["regionid", "regionName"],
        },
        {
          label: "工作年限",
          prop: "gznum",
          inputPlaceholder: "请输入工作年限",
        },
        {
          label: "职务",
          prop: "personZw",
          inputPlaceholder: "请输入职务",
        },
        {
          label: "已服务人数",
          prop: "serviceCount",
          inputPlaceholder: "请输入已服务人数",
        },
        {
          label: "服务手机号",
          prop: "servicePhone",
          inputPlaceholder: "请绑定服务手机号",
        },
        {
          label: "服务邮箱",
          prop: "serviceMail",
          inputPlaceholder: "请绑定服务邮箱",
        },
      ],
      rules: {
        iname: [
          {
            required: true,
            message: "请输入姓名",
            trigger: ["blur", "change"],
          },
        ],
        sex: [
          {
            required: true,
            message: "请选择性别",
          },
        ],
        bday: [
          {
            required: true,
            message: "请选择出生日期",
          },
        ],
        regionid: [
          {
            required: true,
            message: "请选择现居住地",
          },
        ],
        gznum: [
          {
            required: true,
            message: "请输入从业年限",
            trigger: ["blur", "change"],
          },
        ],
        personZw: [
          {
            required: true,
            message: "请输入职务",
            trigger: ["blur", "change"],
          },
        ],
        serviceCount: [
          {
            required: true,
            message: "请输入已服务人数",
            trigger: ["blur", "change"],
          },
        ],
        servicePhone: [
          {
            required: true,
            message: "请输入服务手机号",
            trigger: ["blur", "change"],
          },
        ],
        serviceMail: [
          {
            required: true,
            message: "请输入服务邮箱",
            trigger: ["blur", "change"],
          },
        ],
      },
      loading: false,
      region: [],
    };
  },
  created() {
    uni.$on("uAvatarCropper", (path) => {
      uni.uploadFile({
        url: uploadAction,
        filePath: path,
        name: "file",
        success: (res) => {
          this.form.pic = uploadBaseUrl + res.data;
        },
      });
    });
    
    getFileByUrl('https://img3.job1001.com/ypMp/elan/files/region.min.json').then(res => {
      this.region = insertDefault(res)
    })
  },
  onShow() {
    this.ztConsultantInfoFn();
  },
  onLoad(opt) {},
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    handleShow(item) {
      this.$set(item, "show", false);
    },
    handleRegionName(id) {
      const regionId = id + "";
      if (regionId) {
        let regionPId = regionId.slice(0, 2) + "0000";
        let regionCId = regionId.slice(0, 4) + "00";
        let regionP = this.region.find((ele) => ele.value === regionPId);
        let regionC = regionP.children.find((ele) => ele.value === regionCId);
        return regionP.label + " - " + regionC.label;
      } else {
        return "";
      }
    },
    handleRegionId([data, name], index) {
      if (Array.isArray(name) && Array.isArray(data)) {
        name.forEach((ele, idx) => {
          this.$set(this.form, ele, data[idx]);
        });
      } else {
        this.$set(this.form, name, data);
      }
      this.$set(this.formList[index], "show", false);
    },
    ztConsultantInfoFn() {
      let param = {
        personId: this.personId,
      };
      ztConsultantInfo(param).then((res) => {
        if (res.code == 200) {
          this.form = {
            personId: res.data.personId,
            pic: res.data.pic,
            iname: res.data.iname,
            sex: res.data.sex,
            bday: res.data.bday,
            regionid: res.data.regionid,
            servicePhone: res.data.servicePhone,
            serviceMail: res.data.serviceMail,
            serviceCount: res.data.serviceCount + "",
            gznum: res.data.gznum + "",
            personZw: res.data.personZw,
            regionName: this.handleRegionName(res.data.regionid),
          };
        }
      });
    },
    handleAvatar() {
      uni.navigateTo({
        url: `/pagesSub/resume/cropper/index?destWidth=${600}&rectWidth=${300}`,
      });
    },
    handleSelect(item) {
      if (item.comp) {
        this.$set(item, "show", true);
      }
    },
    handleConfirm(e, item) {
      if (Array.isArray(e)) {
        this.$set(this.form, item.prop, e[0].label);
        if (item.propVal) {
          this.$set(this.form, item.propVal, e[0].value);
        }
      } else {
        let time = `${e.year}-${e.month}-${e.day}`;
        this.$set(this.form, item.prop, time);
      }
      setTimeout(() => {
        this.$refs.uForm.validate();
      }, 0);
    },
    handleCheckBind(item, callback) {
      if (!item.target) {
        return uni.showToast({ icon: "none", title: item.placeholder });
      }
      if (!item.validator(item.target)) {
        return uni.showToast({ icon: "none", title: item.errMsg });
      }
      checkCanBind({ bindContent: item.target }).then((res) => {
        if (callback) callback(res.status === "OK");
      });
    },
    handleBind(item) {
      let param = {
        type: item.type,
        person_id: this.personId,
        authCode: item.code,
      };
      if (item.binded) {
        param.condition = JSON.stringify({
          newupdatebind: 1,
        });
      }
      checkBindCode(param).then((res) => {
        if (+res.code === 200) {
          this.$set(this.form, item.prop, item.target);
          uni.showToast({ icon: "none", title: "绑定成功" });
          this.$set(item, "show", false);
          setTimeout(() => {
            this.$refs.uForm.validate();
          }, 10);
        } else {
          uni.showToast({ icon: "none", title: res.status_desc, duration: 2000 });
        }
      });
    },
    sendBindCode(item, binded) {
      let param = {
        type: item.type,
        person_id: this.personId,
        content: item.target,
        condition: JSON.stringify({
          homename: this.$productName,
        }),
      };
      if (binded) {
        param.condition = JSON.stringify({
          newupdatebind: 1,
          homename: this.$productName,
        });
      }
      sendBindCode(param).then((res) => {
        uni.showToast({ icon: "none", title: res.status_desc, duration: 2000 });
        if (res.status === "OK") {
          let sec = 59;
          this.$set(item, "codeText", `${--sec} s`);
          item.codeTimer = setInterval(() => {
            this.$set(item, "codeText", `${--sec} s`);
            if (sec <= 0) {
              clearInterval(item.codeTimer);
              this.$set(item, "codeTimer", null);
              this.$set(item, "codeText", "获取验证码");
            }
          }, 1000);
        }
      });
    },
    handleCms(item) {
      let that = this;
      if (item.codeTimer) return;
      this.handleCheckBind(item, (bindRes) => {
        if (bindRes) {
          this.sendBindCode(item);
          that.$set(item, "binded", false);
        } else {
          uni.showModal({
            title: "温馨提示",
            content: `该${item.label}已被绑定，继续绑定将导致原有账号不能登录，请慎重操作`,
            success: function (res) {
              if (res.confirm) {
                that.sendBindCode(item, true);
                that.$set(item, "binded", true);
              } else if (res.cancel) {
                return false;
              }
            },
          });
        }
      });
    },
    handleSave() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          if (this.form.bday > formatTime(new Date(), "yyyy-MM-dd")) {
            return uni.showToast({ icon: "none", title: "出生日期有误" });
          }
          this.loading = true;
          const {
            personId,
            pic,
            iname,
            sex,
            bday,
            regionid,
            gznum,
            personZw,
            serviceCount,
            servicePhone,
            serviceMail,
          } = this.form;
          const params = {
            personId,
            pic,
            iname,
            sex,
            bday,
            regionid,
            gznum,
            personZw,
            serviceCount,
            servicePhone,
            serviceMail,
          };
          editConsultant(params).then((res) => {
            if (+res.code === 200) {
              uni.showToast({ icon: "none", title: "修改成功" });
              this.loading = false;
              uni.navigateBack();
            }
          });
        } else {
          uni.showToast({ icon: "none", title: "请完善信息后保存" });
        }
      });
    },
    uploadAvatar(imgUrl) {
      let params = {
        person_id: this.personId,
        imgurl: uploadBaseUrl + imgUrl,
      };
      uploadAvatar(params).then((res) => {
        if (res.code != 200) {
          uni.showToast({ icon: "none", title: "头像上传失败" });
        }
      });
    },
  },
};
</script>

<style lang="scss">
.basic {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 32rpx 32rpx 36rpx;
  box-sizing: border-box;
  .basic-form-wrap {
    flex-grow: 1;
    ::v-deep .u-form {
      padding: 0 32rpx;
      background: $uni-bg-color;
      border-radius: 24rpx;
      .u-form-item {
        .btn-group {
          padding: 0 24rpx;
          line-height: 102rpx;
          .cancel,
          .confirm {
            padding: 0 16rpx;
          }
        }
      }
    }
  }
  .save-btn {
    flex-shrink: 0;
    margin: 82rpx 0 4rpx;
    width: 100%;
  }
}
</style>
<style lang="scss">
.avatar-wrap {
  padding: 32rpx 0 !important;
  ::v-deep .u-form-item--left {
    display: none;
  }
  ::v-deep .u-form-item--right__content__slot {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .label {
      font-size: $uni-font-size-big;
    }
    .avatar {
      margin-top: 12rpx;
      width: 96rpx;
      height: 96rpx;
      border-radius: 50%;
      color: $uni-text-color-222;
    }
  }
}
.form-cms {
  ::v-deep .fc-wrap {
    padding: 0 32rpx 32rpx;
    box-sizing: border-box;
    .title {
      line-height: 90rpx;
      text-align: center;
      font-size: $uni-font-size-lg;
    }
    .u-field {
      padding: 24rpx 0;
    }
    .send-code {
      color: $u-type-primary;
    }
    .confirm-btn {
      margin-top: 44rpx;
    }
  }
}
</style>
